package cn.tnar.yunpark.io;

import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 一种重试策略: 永久重试，每次重试前等待一会
 * Created by tieh on 2017/6/21.
 */
public class RetryForeverWithDelay implements io.reactivex.functions.Function<Flowable<Throwable>, Publisher<?>> {

    private static final Logger log = LoggerFactory.getLogger(RetryForeverWithDelay.class);

    private long delay;
    private TimeUnit unit;
    private final Scheduler scheduler;

    public RetryForeverWithDelay(long delay, TimeUnit unit, Scheduler scheduler) {
        this.delay = delay;
        this.unit = unit;
        this.scheduler = scheduler;
    }

    @Override
    public Publisher<?> apply(Flowable<Throwable> attempts) {
        return attempts.flatMap((e) -> {
            log.info("Sleep " + delay + " " + unit + " before retry");
            return Flowable.timer(delay, unit, scheduler);
        });
    }
}
